package com.future.hedongjun.home.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.dl7.player.media.IjkPlayerView;
import com.dl7.player.utils.SoftInputUtils;
import com.future.baselib.activity.BaseActivity;
import com.future.baselib.adapter.FragmentAdapter;
import com.future.baselib.entity.BaseResponse;
import com.future.baselib.http.HttpRequest;
import com.future.baselib.utils.EventBusUtil;
import com.future.baselib.utils.ToastUtils;
import com.future.baselib.view.IosAlertDialog;
import com.future.hedongjun.R;
import com.future.hedongjun.common.MyApp;
import com.future.hedongjun.home.adapter.ClassHourAdapter;
import com.future.hedongjun.home.bean.ClassDetail;
import com.future.hedongjun.home.bean.ClassIntroduceBean;
import com.future.hedongjun.home.bean.response.ClassHourResponse;
import com.future.hedongjun.home.bean.response.ClassIntroduceResponse;
import com.future.hedongjun.home.fragment.ClassCoursewareFragment;
import com.future.hedongjun.home.fragment.ClassHourFragment;
import com.future.hedongjun.home.fragment.ClassIntroduceFragment;
import com.future.hedongjun.home.utils.DES;
import com.future.hedongjun.home.utils.DanMaKuSendDialog;
import com.future.hedongjun.home.utils.IndicatorLineUtil;
import com.future.hedongjun.mine.order.ConfirmClassOrderActivity;
import com.future.hedongjun.mine.ui.FreeVideoActivity;
import com.future.hedongjun.mine.ui.LoginActivity;
import com.jaeger.library.StatusBarUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;

import static com.mob.MobSDK.getContext;

public class ClassDetailActivity extends AppCompatActivity {
    @BindView(R.id.tv_back)
    TextView tvBack;
    @BindView(R.id.Ijk_detailPlayer)
    IjkPlayerView IjkDetailPlayer;
    @BindView(R.id.btn_watch_freeClass)
    Button btnWatchFreeClass;
    @BindView(R.id.btn_buy_class)
    Button btnBuyClass;
    @BindView(R.id.tv_classTitle)
    TextView tvClassTitle;
    @BindView(R.id.tv_classPrice)
    TextView tvClassPrice;
    @BindView(R.id.tv_classVoice)
    TextView tvClassVoice;
    @BindView(R.id.rl_classInfo)
    RelativeLayout rlClassInfo;
    @BindView(R.id.vp_classContent)
    ViewPager vpClassContent;
    @BindView(R.id.tb_classTab)
    TabLayout tbClassTab;
    @BindView(R.id.rl_classDetail)
    RelativeLayout mEtLayout;
    @BindView(R.id.rl_bar)
    RelativeLayout rlBar;
    @BindView(R.id.tv_danMu)
    TextView tvDanMu;
    @BindView(R.id.cb_danMuSwitch)
    CheckBox cbDanMuSwitch;
    @BindView(R.id.rl_danMu)
    RelativeLayout rlDanMu;
    @BindView(R.id.ll_ClassBuy)
    LinearLayout llClassBuy;
    private boolean mIsFocus;
    private String[] tabTitle = {"介绍", "课时", "课件"};
    private String id;
    private FragmentAdapter fragmentAdapter;
    private List<Fragment> fragmentList;
    private DanMaKuSendDialog danMaKuSendDialog;
    private ClassHourFragment classHourFragment;
    private String classId;
    private ClassIntroduceFragment classIntroduceFragment;
    private ClassCoursewareFragment classCoursewareFragment;
    private String buy_status;


    private String classUrl;
    private String className;
    private ClassIntroduceBean classIntroduceBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        if (TextUtils.isEmpty(id)) {
//            toast("id为空");
//            finish();
//            return;
//        }
        setContentView(R.layout.activity_class_detail);
        ButterKnife.bind(this);
        //课程ID
        classId = getIntent().getStringExtra("id");
        //自定义弹幕输入框
        danMaKuSendDialog = new DanMaKuSendDialog(this);
        //视频播放器初始化
        initIjkVideo();
        //初始化tabLayout
        initTabLayout();
        getData();
    }

    private void initTabLayout() {
        fragmentList = new ArrayList<>();
        classHourFragment = new ClassHourFragment();
        classIntroduceFragment = new ClassIntroduceFragment();
        classCoursewareFragment = new ClassCoursewareFragment();
        fragmentList.add(classIntroduceFragment);
        fragmentList.add(classHourFragment);
        fragmentList.add(classCoursewareFragment);
        fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(), fragmentList);
        vpClassContent.setAdapter(fragmentAdapter);
        tbClassTab.setupWithViewPager(vpClassContent);
        for (int i = 0; i < tabTitle.length; i++) {
            tbClassTab.getTabAt(i).setText(tabTitle[i]);
        }
        tbClassTab.post(new Runnable() {
            @Override
            public void run() {
                IndicatorLineUtil.setIndicator(tbClassTab, 40, 40);
            }
        });
        classIntroduceFragment.setClassId(classId);
        classCoursewareFragment.setClassId(classId);
        classHourFragment.setIjkVideo(IjkDetailPlayer, classId);
    }

    private void initIjkVideo() {
        IjkDetailPlayer.init(); // Initialize, the first to use

        //顶部Bar
        IjkDetailPlayer.setViewBar(rlBar);
        //课程分享
        IjkDetailPlayer.ShareOnClickItem(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showShare("11", "22", "33", "44");
            }
        });
        //课程开始
        IjkDetailPlayer.StartOnclickItem(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!buy_status.equals("3")) {
                    new IosAlertDialog(ClassDetailActivity.this)
                            .builder()
                            .setMsg("请先购买课程后,才能实用哟!")
                            .setNegativeButton("考虑一下", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {

                                }
                            })
                            .setPositiveButton("立即购买", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (classIntroduceBean != null) {
                                        ClassDetail detail = new ClassDetail();
                                        detail.setId(classIntroduceBean.id);
                                        detail.setName(classIntroduceBean.name);
                                        detail.setLogo_img(classIntroduceBean.name);
                                        double price = 0;
                                        try {
                                            price = Double.valueOf(classIntroduceBean.price);
                                        } catch (NumberFormatException e) {

                                        }
                                        detail.setPrice(price);
                                        ConfirmClassOrderActivity.open(ClassDetailActivity.this, detail);
                                    }
                                }
                            }).show();
                }
            }
        });
        //弹幕开关
        cbDanMuSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    IjkDetailPlayer.showOrHideDanmaku(true);
                } else {
                    IjkDetailPlayer.showOrHideDanmaku(false);
                }
            }
        });
        //视频播放时显示弹幕输入框
        IjkDetailPlayer.setDanMuView(rlDanMu, llClassBuy);
    }

    @Override
    protected void onResume() {
        super.onResume();
        IjkDetailPlayer.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        IjkDetailPlayer.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        IjkDetailPlayer.onDestroy();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        IjkDetailPlayer.configurationChanged(newConfig);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (IjkDetailPlayer.handleVolumeKey(keyCode)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (IjkDetailPlayer.onBackPressed()) {
            return;
        }
        super.onBackPressed();
    }


    @OnClick({R.id.tv_back, R.id.tv_classVoice, R.id.vp_classContent, R.id.btn_watch_freeClass, R.id.btn_buy_class, R.id.tv_danMu})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_classVoice:
                Intent toVoice = new Intent(this, ClassVoiceActivity.class);
                toVoice.putExtra("classId", classId);
                startActivity(toVoice);
                finish();
                break;
            case R.id.vp_classContent:
                break;
            case R.id.btn_watch_freeClass:
                Intent toVoide = new Intent(this, FreeVideoActivity.class);
                toVoide.putExtra("VideoUrl", classUrl);
                toVoide.putExtra("VideoName", className);
                startActivity(toVoide);
                break;
            case R.id.btn_buy_class:
                if (classIntroduceBean != null) {
                    ClassDetail detail = new ClassDetail();
                    detail.setId(classIntroduceBean.id);
                    detail.setName(classIntroduceBean.name);
                    detail.setLogo_img(classIntroduceBean.name);
                    double price = 0;
                    try {
                        price = Double.valueOf(classIntroduceBean.price);
                    } catch (NumberFormatException e) {

                    }
                    detail.setPrice(price);
                    ConfirmClassOrderActivity.open(this, detail);
                }
                break;
            case R.id.tv_back:
                finish();
                break;
            case R.id.tv_danMu:
                danMaKuSendDialog.show();
                if (IjkDetailPlayer != null) {
                    danMaKuSendDialog.setIjkVideo(IjkDetailPlayer, classId);
                }
                break;
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        View view = getCurrentFocus();
        if (_isHideSoftInput(view, (int) ev.getX(), (int) ev.getY())) {
            _closeSoftInput();
            return true;
        }
        return super.dispatchTouchEvent(ev);
    }

    private void _closeSoftInput() {
        SoftInputUtils.closeSoftInput(this);
        IjkDetailPlayer.recoverFromEditVideo();
    }

    private boolean _isHideSoftInput(View view, int x, int y) {
        if (view == null || !(view instanceof EditText) || !mIsFocus) {
            return false;
        }
        return x < mEtLayout.getLeft() ||
                x > mEtLayout.getRight() ||
                y < mEtLayout.getTop();
    }

    public void getData() {
        if (MyApp.getInstance().getUserToken().isEmpty()) {
            startActivity(new Intent(ClassDetailActivity.this, LoginActivity.class));
        } else {
            new HttpRequest<ClassIntroduceResponse>()
                    .with(getContext())
                    .setApiCode("_classdetail_001")
                    .addParam("id", classId)
                    .addParam("userToken", MyApp.getInstance().getUserToken())
                    .addSuccessListener(new HttpRequest.OnNetworkSuccess() {
                        @Override
                        public void onSuccess(BaseResponse response) {
                            classIntroduceBean = ((ClassIntroduceResponse) response).data.get(0);
                            tvClassTitle.setText(classIntroduceBean.name);
                            tvClassPrice.setText(classIntroduceBean.price);
                            Glide.with(ClassDetailActivity.this).load(classIntroduceBean.imgUrl).into(IjkDetailPlayer.mPlayerThumb); // Show the thumb before play
                            buy_status = classIntroduceBean.buy_status;
                            classUrl = classIntroduceBean.tutor_url;
                            className = classIntroduceBean.name;
                        }
                    }).start(new ClassIntroduceResponse());
        }
    }


    public void showShare(final String title, final String content, final String url, final String imgUrl) {
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // 分享时Notification的图标和文字  2.5.9以后的版本不     调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {
            @Override
            public void onShare(Platform platform, Platform.ShareParams paramsToShare) {
                if ("Wechat".equals(platform.getName())) {
                    paramsToShare.setTitle(title);
                    paramsToShare.setUrl(url);
                    paramsToShare.setText(content);
                    paramsToShare.setImageUrl(imgUrl);
                    paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
                }
                if ("WechatMoments".equals(platform.getName())) {
                    paramsToShare.setTitle(title);
                    paramsToShare.setUrl(url);
                    paramsToShare.setText(content);
                    paramsToShare.setImageUrl(imgUrl);
                    paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
                }
                if ("QQ".equals(platform.getName())) {
                    paramsToShare.setTitle(title);
                    paramsToShare.setTitleUrl(url);
                    paramsToShare.setText(content);
                    paramsToShare.setImageUrl(imgUrl);
                }
                if ("QZone".equals(platform.getName())) {
                    paramsToShare.setTitle(title);
                    paramsToShare.setTitleUrl(url);
                    paramsToShare.setText(content);
                    paramsToShare.setImageUrl(imgUrl);
                }
            }
        });

        oks.setCallback(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                ToastUtils.longToast(getContext(), "分享成功");
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                ToastUtils.longToast(getContext(), "分享失败");
            }

            @Override
            public void onCancel(Platform platform, int i) {
                ToastUtils.longToast(getContext(), "分享取消");

            }
        });

        // 启动分享GUI
        oks.show(this);
    }
}
